package cn.bincker.mybatis.encrypt.data.migration.entity;

import lombok.Data;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

@Data
public class MigrateTable {
    /**
     * src schema
     */
    private String srcSchema;
    /**
     * dist schema
     */
    private String distSchema;
    /**
     * 源表名
     */
    private String srcName;
    /**
     * 目标表名
     */
    private String distName;
    /**
     * 实体类
     */
    private Class<?> entityClass;
    /**
     * 更新时间字段
     */
    private String updatedTimeColumnName;

    private List<ColumnInfo> columns;

    private List<ColumnInfo> keys;

    private List<ColumnInfo> encryptColumns;

    private long totalRows;

    private AtomicLong migratedRows = new AtomicLong();

    public MigrateTable() {
    }

    public String getSrcTableName(){
        if (srcSchema == null || srcSchema.isBlank()) return srcName;
        return srcSchema + "." + srcName;
    }

    public String getDistTableName(){
        if (distSchema == null || distSchema.isBlank()) return distName;
        return distSchema + "." + distName;
    }

    public String getSrcTableSqlName(){
        if (srcSchema == null || srcSchema.isBlank()) return "\"" + srcName + "\"";
        return "\"" + srcSchema + "\".\"" + srcName + "\"";
    }

    public String getDistTableSqlName(){
        if (distSchema == null || distSchema.isBlank()) return "\"" + distName + "\"";
        return "\"" + distSchema + "\".\"" + distName + "\"";
    }

    public void setColumns(List<ColumnInfo> columns) {
        this.columns = columns;
        keys = columns.stream().filter(ColumnInfo::isPrimaryKey).collect(Collectors.toList());
        encryptColumns = columns.stream().filter(ColumnInfo::isEncrypt).collect(Collectors.toList());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MigrateTable that = (MigrateTable) o;
        return Objects.equals(srcSchema, that.srcSchema) && Objects.equals(srcName, that.srcName);
    }

    @Override
    public int hashCode() {
        return Objects.hash(srcSchema, srcName);
    }
}
